package cn.aishua.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.util.Log;
import cn.aishua.location.Locator;
import cn.aishua.util.FormatConverter;

import com.baidu.location.BDLocation;

public class HttpRequestUtil
{
    public static final String HTTP_METHOD_GET = "http_get";
    public static final String HTTP_METHOD_POST = "http_post";
    public static final String HTTP_METHOD_DELETE = "http_delete";
    public static final String HTTP_METHOD_PUT = "http_put";

    //    public static final String CHARSET_UTF8 = "UTF-8";
    public static final int CONNECTION_TIME_OUT_MILLIS = 20000;
    public static final int RESPONSE_TIME_OUT_MILLIS = 25000;

    //    public static final String URL_HOST = "http://g.hiphotos.baidu.com";
    //    public static final String URL_HOST = "http://192.168.1.109:3000";
    public static final String URL_HOST = "http://www.aishua.cn:8888";
    //    public static final String URL_IMAGE_HOST = "http://img1.aishua.cn:8888";

    public static final String URL_JSON_LOGIN = "/sessions.json";
    public static final String URL_JSON_LOGOUT = "/logout.json";
    public static final String URL_JSON_SEND_REG_CAPTCHA = "/account/users/reg_captcha.json";
    public static final String URL_JSON_VALID_REG_CAPTCHA = "/account/users/valid_reg_captcha.json";
    public static final String URL_JSON_REGISTER = "/account/users.json";
    public static final String URL_JSON_ACCOUNT_INFO = "/account/information.json";
    public static final String URL_JSON_BANK_CARDS = "/account/bank_cards.json";
    public static final String URL_JSON_CREDIT_CASHING = "/account/credit_cashing_applications.json";
    public static final String URL_JSON_SEND_CASHING_CAPTCHA = "/account/credit_cashing_applications/send_captcha.json";
    public static final String URL_JSON_CREDIT_ACCOUNTS = "/account/credit_accounts.json";

    public static final String URL_JSON_MERCHANT = "/merchant/";
    public static final String URL_JSON_SHAKE = "/merchant/shake.json";
    public static final String URL_JSON_FIND_VENDOR = "/merchant.json";
    public static final String URL_JSON_NEARBY_VENDOR = "/merchant/nearby.json";
    public static final String URL_JSON_HOME = "/home.json";
    public static final String URL_JSON_RECOMMAND = "/merchant/recommend.json";
    public static final String URL_JSON_RESOURCES = "/merchant/resources.json";
    public static final String URL_JSON_BANK_LIST = "/card.json";
    public static final String URL_JSON_APK_VERSION = "/apk/version.json";

    public static HttpRequestUtil instance;

    private DefaultHttpClient httpClient;

    //    private HttpUriRequest currRequest;

    private HttpRequestUtil()
    {

    }

    public static synchronized HttpRequestUtil getInstance()
    {
        Log.d( "HttpRequestUtil", "getInstance()" );
        if( instance == null )
        {
            Log.d( "HttpRequestUtil", "instance == null" );
            instance = new HttpRequestUtil();

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 );
            HttpProtocolParams.setContentCharset( params, HTTP.UTF_8 );
            HttpProtocolParams.setUseExpectContinue( params, true );
            HttpProtocolParams.setUserAgent( params, "android" );

            ConnManagerParams.setTimeout( params, CONNECTION_TIME_OUT_MILLIS );
            // connection timeout: 20s
            HttpConnectionParams.setConnectionTimeout( params, CONNECTION_TIME_OUT_MILLIS );
            // request timeout: 40s
            HttpConnectionParams.setSoTimeout( params, RESPONSE_TIME_OUT_MILLIS );
            //            HttpConnectionParams.setConnectionTimeout( params, CONNECTION_TIME_OUT_MILLIS );

            ConnManagerParams.setMaxTotalConnections( params, 2 );

            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register( new Scheme( "http", PlainSocketFactory.getSocketFactory(), 80 ) );
            schReg.register( new Scheme( "https", SSLSocketFactory.getSocketFactory(), 443 ) );

            ClientConnectionManager conMgr = new ThreadSafeClientConnManager( params, schReg );

            instance.httpClient = new DefaultHttpClient( conMgr, params );
            //            HttpParams params = instance.httpClient.getParams();
            //            params.setParameter( CoreProtocolPNames.HTTP_CONTENT_CHARSET, CHARSET_UTF8 );
            //            HttpConnectionParams.setConnectionTimeout( params, CONNECTION_TIME_OUT_MILLIS );
        }
        return instance;
    }

    /**
     * http post/put request
     * 
     * @param url
     *            URL of service
     * @param params
     * 
     * @return
     * @throws Exception
     */
    public HttpResponse request( String url, List<NameValuePair> params, String httpMethod )
    {
        Log.d( "http request", httpMethod );
        Log.d( "request url", url );
        //        url = "";
        if( params != null )
        {
            for( NameValuePair nameValuePair : params )
            {
                Log.d( "parameter", nameValuePair.getName() + "-" + nameValuePair.getValue() );
            }
        }

        HttpEntityEnclosingRequestBase httpReq = null;

        String fullUrl = URL_HOST + url;

        if( HTTP_METHOD_PUT.equals( httpMethod ) )
        {
            httpReq = new HttpPut( fullUrl );
        }
        else if( HTTP_METHOD_POST.equals( httpMethod ) )
        {
            httpReq = new HttpPost( fullUrl );
        }
        else
        {
            Log.e( "HttpRequestUtil", "Incorrect http method parameter" );
            return null;
        }

        /**
         * take this http request as current http request so that we can abort this request
         */
        //        currRequest = httpReq;

        HttpResponse httpRes = null;

        try
        {
            //            httpReq.setHeader( "User-Agent", "android" );
            if( params != null && params.size() > 0 )
            {
                httpReq.setEntity( new UrlEncodedFormEntity( params, HTTP.UTF_8 ) );
            }
            httpRes = httpClient.execute( httpReq );
        }
        catch( UnsupportedEncodingException e )
        {
            Log.e( "HttpRequestUtil", e.getMessage() );
        }
        catch( IOException e )
        {
            if( e instanceof ConnectTimeoutException )
            {
                throw new RuntimeException( "连接超时，请检查网络" );
            }
            else if( e instanceof SocketTimeoutException )
            {
                throw new RuntimeException( "请求超时，请检查网络" );
            }
            else
            {
                Log.e( "HttpRequestUtil", e.getMessage() );
            }
        }
        catch( Exception e )
        {
            Log.e( "HttpRequestUtil", e.getMessage() );
        }

        return httpRes;
    }

    /**
     * http get/delete request
     * 
     * @param url
     *            URL of service including parameters
     * @param httpMethod
     * 
     * @return
     * @throws Exception
     */
    public HttpResponse request( String url, String httpMethod )
    {
        Log.d( "http request", httpMethod );
        Log.d( "request url", url );
        //        url = "";
        HttpUriRequest req = null;
        HttpResponse res = null;

        if( HTTP_METHOD_GET.equals( httpMethod ) )
        {
            req = new HttpGet( URL_HOST + url );
        }
        else if( HTTP_METHOD_DELETE.equals( httpMethod ) )
        {
            req = new HttpDelete( URL_HOST + url );
        }
        else
        {
            Log.e( "HttpRequestUtil", "Incorrect http method parameter" );
            return null;
        }

        /**
         * take this http request as current http request so that we can abort this request
         */
        //        currRequest = req;

        try
        {
            //            req.setHeader( "User-Agent", "android" );
            res = httpClient.execute( req );
        }
        catch( IOException e )
        {
            if( e instanceof ConnectTimeoutException )
            {
                throw new RuntimeException( "连接超时，请检查网络" );
            }
            else if( e instanceof SocketTimeoutException )
            {
                throw new RuntimeException( "请求超时，请检查网络" );
            }
            else
            {
                Log.e( "HttpRequestUtil", e.getMessage() );
            }
        }
        catch( Exception e )
        {
            Log.e( "HttpRequestUtil", e.getMessage() );
        }

        return res;
    }

    public void clearCookies()
    {
        if( httpClient != null )
        {
            httpClient.getCookieStore().clear();
        }
    }

    //    public void abort()
    //    {
    //        if( currRequest != null && !currRequest.isAborted() )
    //        {
    //            Log.d( "HttpRequestUtil", "current request is not null" );
    //            currRequest.abort();
    //        }
    //    }

    //    public static void abortRequest( final HttpUriRequest request )
    //    {
    //        Log.d( "HttpRequestUtil", "abort request" );
    //        if( request != null && !request.isAborted() )
    //        {
    //            Log.d( "HttpRequestUtil", "haven't been aborted" );
    //            request.abort();
    //        }
    //    }

    /**
     * 
     * @param paramArray
     *            account_name:xxx, password:xxx
     * @return
     */
    public HttpResponse login( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "account_name", paramArray[0] ) );
        params.add( new BasicNameValuePair( "password", paramArray[1] ) );
        params.add( new BasicNameValuePair( "remember_me", "1" ) );
        HttpResponse res = request( URL_JSON_LOGIN, params, HTTP_METHOD_POST );

        return res;
    }

    public HttpResponse getUserinfo()
    {
        HttpResponse res = request( URL_JSON_ACCOUNT_INFO, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse logout()
    {
        HttpResponse res = request( URL_JSON_LOGOUT, HTTP_METHOD_DELETE );
        httpClient.getCookieStore().clear();
        return res;
    }

    /**
     * 
     * @param paramArray
     *            mobile=xxx
     * @return
     */
    public HttpResponse sendRegCaptcha( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "mobile", paramArray[0] ) );
        HttpResponse res = request( URL_JSON_SEND_REG_CAPTCHA, params, HTTP_METHOD_POST );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            captcha:xxx mobile:xxx
     * @return
     */
    public HttpResponse validateRegCapcha( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "captcha", paramArray[0] ) );
        params.add( new BasicNameValuePair( "mobile", paramArray[1] ) );
        HttpResponse res = request( URL_JSON_VALID_REG_CAPTCHA, params, HTTP_METHOD_POST );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            account_name:xxx, password:xxx, password_confirmation:xxx, captcha:xxx,
     *            mobile:xxx, referer:xxx
     * @return
     */
    public HttpResponse register( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "account_name", paramArray[0] ) );
        params.add( new BasicNameValuePair( "password", paramArray[1] ) );
        params.add( new BasicNameValuePair( "password_confirmation", paramArray[2] ) );
        params.add( new BasicNameValuePair( "captcha", paramArray[3] ) );
        params.add( new BasicNameValuePair( "mobile", paramArray[4] ) );
        params.add( new BasicNameValuePair( "referer", paramArray[5] ) );
        HttpResponse res = request( URL_JSON_REGISTER, params, HTTP_METHOD_POST );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            user[real_name]:xxx, user_information[province]:xxx, user_information[city]:xxx,
     *            user_information[county]:xxx, user_information[gender]:xxx,
     *            user_information[birthday]:2013-01-01, user_information[email]:xxx,
     *            user_information[im_qq]:xxx user_information[address]:xxx
     * 
     * @return
     */
    public HttpResponse completeUserInfo( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "user[real_name]", paramArray[0] ) );
        params.add( new BasicNameValuePair( "user_information[province]", paramArray[1] ) );
        params.add( new BasicNameValuePair( "user_information[city]", paramArray[2] ) );
        params.add( new BasicNameValuePair( "user_information[county]", paramArray[3] ) );
        params.add( new BasicNameValuePair( "user_information[gender]", paramArray[4] ) );
        params.add( new BasicNameValuePair( "user_information[birthday]", paramArray[5] ) );
        params.add( new BasicNameValuePair( "user_information[address]", paramArray[6] ) );
        HttpResponse res = request( URL_JSON_ACCOUNT_INFO, params, HTTP_METHOD_PUT );
        return res;
    }

    /**
     * 
     * @return JSON response:
     *         {"bank_card":[{"id":2,"card_number":"123456789012","card_type":0,"bank_display_name"
     *         :"其他银行"
     *         ,"created_at":"2012-09-10T15:58:18Z","cashing_card":true,"credit_earned":90000}]}
     */
    public HttpResponse getBankCards()
    {
        return request( URL_JSON_BANK_CARDS, HTTP_METHOD_GET );
    }

    /**
     * 
     * @param paramArray
     *            update_action:xxx(enter-设置, cancel-取消), bank_card_id:xxx
     * @return
     */
    public HttpResponse setCashingCard( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "update_action", paramArray[0] ) );
        params.add( new BasicNameValuePair( "bank_card_id", paramArray[1] ) );
        HttpResponse res = request( URL_JSON_BANK_CARDS, params, HTTP_METHOD_PUT );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            bank_card_id:xxx
     * @return
     */
    public HttpResponse removeBankCard( String[] paramArray )
    {
        HttpResponse res = request( URL_JSON_BANK_CARDS + "?bank_card_id=" + paramArray[0], HTTP_METHOD_DELETE );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            card_company:xxx, card_type:xxx, num:xxx, card_number:xxx
     * 
     * @return
     */
    public HttpResponse addBankCard( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "card_company", paramArray[0] ) );
        params.add( new BasicNameValuePair( "card_type", paramArray[1] ) );
        params.add( new BasicNameValuePair( "card_number", paramArray[2] ) );
        HttpResponse res = request( URL_JSON_BANK_CARDS, params, HTTP_METHOD_POST );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            amount:xxx, captcha:xxx
     * @return
     */
    public HttpResponse cashCredit( String[] paramArray )
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add( new BasicNameValuePair( "amount", paramArray[0] ) );
        params.add( new BasicNameValuePair( "captcha", paramArray[1] ) );
        HttpResponse res = request( URL_JSON_CREDIT_CASHING, params, HTTP_METHOD_POST );
        return res;
    }

    public HttpResponse sendCashingCaptcha()
    {
        HttpResponse res = request( URL_JSON_SEND_CASHING_CAPTCHA, null, HTTP_METHOD_POST );
        return res;
    }

    /**
     * 
     * @return JSON response:
     *         {"card_info":{"usable_credit":85000,"card_number":"123456789012","bank_display_name"
     *         :"其他银行" ,"mobile":"13981842940"}}
     */
    public HttpResponse getCashingCredit()
    {
        HttpResponse res = request( URL_JSON_CREDIT_CASHING, HTTP_METHOD_GET );
        return res;
    }

    /**
     * 
     * @return JSON response:
     *         {"total":4,"user":{"usable_credit":85000,"locked_credit":5000,"total_credit"
     *         :90000,"cashed_credit"
     *         :0},"log":[{"transaction_datetime":"2013-02-25T15:23:46Z","store_name"
     *         :"123","bank_card":"123456789012","money_amount":"2000.0","consumer_credit":30000},{
     *         "transaction_datetime"
     *         :"2012-09-11T12:16:32Z","store_name":"123","bank_card":"123456789012"
     *         ,"money_amount":"1000.0"
     *         ,"consumer_credit":15000},{"transaction_datetime":"2012-09-10T14:07:21Z"
     *         ,"store_name":
     *         "123","bank_card":"123456789012","money_amount":"2000.0","consumer_credit"
     *         :30000},{"transaction_datetime"
     *         :"2012-09-10T14:05:04Z","store_name":"123","bank_card":
     *         "123456789012","money_amount":"1000.0","consumer_credit":15000}]}
     */
    public HttpResponse getCreditAccounts()
    {
        HttpResponse res = request( URL_JSON_CREDIT_ACCOUNTS, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getVendorDetail( String[] paramArray )
    {
        String requestUrl = null;
        if( paramArray[1] != null ) // x and y will only be provided when latitude and longitude are provided
        {
            requestUrl = URL_JSON_MERCHANT + paramArray[0] + ".json?x=" + paramArray[1] + "&y=" + paramArray[2];
        }
        else
        {
            requestUrl = URL_JSON_MERCHANT + paramArray[0] + ".json";
        }

        HttpResponse res = request( requestUrl, HTTP_METHOD_GET );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            merchant_name:xxx, parent_categories[]:xxx, sub_categories[]:xxx, cantons[]:xxx ,
     *            business_circles[]:xxx, average_price[]:xxx-xxx, max_customer_rate[]:xx-xx,
     *            page:x, sort:x
     * @return
     */
    public HttpResponse findVendors( String[] paramArray )
    {
        StringBuffer sbRequetUrl = null;

        boolean useNearbyIntf = "500".equals( paramArray[4] ) || "1000".equals( paramArray[4] )
            || "2000".equals( paramArray[4] );
        BDLocation location = Locator.getInstance( null ).getLocation();
        String x = "" + location.getLatitude();
        String y = "" + location.getLongitude();

        String gpsAttitude = "?x=" + x + "&y=" + y + "&";

        if( useNearbyIntf ) // user nearby interface
        {

            sbRequetUrl = new StringBuffer( URL_JSON_NEARBY_VENDOR + gpsAttitude + "distance=" + paramArray[4] + "&" );
        }
        else
        {
            sbRequetUrl = new StringBuffer( URL_JSON_FIND_VENDOR + gpsAttitude + "limit=10&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[0] ) )
        {
            sbRequetUrl.append( "merchant_name=" + paramArray[0] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[1] ) && !"0".equals( paramArray[1] ) )
        {
            sbRequetUrl.append( "parent_categories[]=" + paramArray[1] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[2] ) && !"0".equals( paramArray[2] ) )
        {
            sbRequetUrl.append( "sub_categories[]=" + paramArray[2] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[3] ) && !"0".equals( paramArray[3] ) )
        {
            sbRequetUrl.append( "cantons[]=" + paramArray[3] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[4] ) && !"0".equals( paramArray[4] ) && !useNearbyIntf )
        {
            sbRequetUrl.append( "business_circles[]=" + paramArray[4] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[5] ) )
        {
            sbRequetUrl.append( "average_price[]=" + paramArray[5] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[6] ) )
        {
            sbRequetUrl.append( "max_customer_rate[]=" + paramArray[6] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[7] ) && !useNearbyIntf ) // paging is unable when using nearby interface
        {
            sbRequetUrl.append( "page=" + paramArray[7] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[8] ) )
        {
            sbRequetUrl.append( "sort=" + paramArray[8] + "&" );
        }

        // remove redundant character & or ?
        if( sbRequetUrl.lastIndexOf( "&", sbRequetUrl.length() - 1 ) != -1
            || sbRequetUrl.lastIndexOf( "?", sbRequetUrl.length() - 1 ) != -1 )
        {
            sbRequetUrl.deleteCharAt( sbRequetUrl.length() - 1 );
        }

        HttpResponse res = request( sbRequetUrl.toString(), HTTP_METHOD_GET );
        return res;
    }

    /**
     * 
     * @param paramArray
     *            parent_categories[]=4 sub_categories[]=27 average_price[] max_customer_rate[]=40
     * @return
     */
    public HttpResponse haveAShake( String[] paramArray )
    {
        BDLocation location = Locator.getInstance( null ).getLocation();
        String x = "" + location.getLatitude();
        String y = "" + location.getLongitude();

        StringBuffer sbRequestUrl = new StringBuffer( URL_JSON_SHAKE + "?x=" + x + "&y=" + y + "&distance=10000&" );

        if( FormatConverter.isNotEmptyString( paramArray[0] ) && !"0".equals( paramArray[0] ) )
        {
            sbRequestUrl.append( "parent_categories[]=" + paramArray[0] + "&" );
        }
        if( FormatConverter.isNotEmptyString( paramArray[1] ) && !"0".equals( paramArray[1] ) )
        {
            sbRequestUrl.append( "sub_categories[]=" + paramArray[1] + "&" );
        }
        if( FormatConverter.isNotEmptyString( paramArray[2] ) )
        {
            sbRequestUrl.append( "average_price[]=" + paramArray[2] + "&" );
        }
        if( FormatConverter.isNotEmptyString( paramArray[3] ) )
        {
            sbRequestUrl.append( "max_customer_rate[]=" + paramArray[3] + "&" );
        }

        // remove redundant character & or ?
        if( sbRequestUrl.lastIndexOf( "&", sbRequestUrl.length() - 1 ) != -1
            || sbRequestUrl.lastIndexOf( "?", sbRequestUrl.length() - 1 ) != -1 )
        {
            sbRequestUrl.deleteCharAt( sbRequestUrl.length() - 1 );
        }
        //        if( paramArray[0] != null ) // x and y will only be provided when latitude and longitude are provided
        //        {
        //            requestUrl = URL_JSON_SHAKE + "?x=" + paramArray[0] + "&y=" + paramArray[1];
        //        }
        //        else
        //        {
        //            requestUrl = URL_JSON_SHAKE;
        //        }

        HttpResponse res = request( sbRequestUrl.toString(), HTTP_METHOD_GET );
        return res;
    }

    private HttpResponse mockSucc()
    {
        HttpResponse response = null;

        try
        {
            Thread.sleep( 1000 );
            response = new BasicHttpResponse( new StatusLine()
            {

                public int getStatusCode()
                {

                    return 200;
                }

                public String getReasonPhrase()
                {
                    return null;
                }

                public ProtocolVersion getProtocolVersion()
                {
                    return null;
                }
            } );
        }
        catch( InterruptedException e )
        {
            e.printStackTrace();
        }
        return response;
    }

    private HttpResponse mock403()
    {
        HttpResponse response = null;

        try
        {
            Thread.sleep( 1000 );
            response = new BasicHttpResponse( new StatusLine()
            {

                public int getStatusCode()
                {

                    return 403;
                }

                public String getReasonPhrase()
                {
                    return null;
                }

                public ProtocolVersion getProtocolVersion()
                {
                    return null;
                }
            } );
        }
        catch( InterruptedException e )
        {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 
     * @param paramArray
     *            merchant_name:xxx, parent_categories[]:xxx, sub_categories[]:xxx, cantons[]:xxx ,
     *            business_circles[]:xxx, average_price[]:xxx-xxx, max_customer_rate[]:xx-xx,
     *            select_type: x, distance:xx, sort:x,
     * @return
     */
    public HttpResponse findNearbyVendors( String[] paramArray )
    {
        StringBuffer sbRequetUrl = new StringBuffer( URL_JSON_NEARBY_VENDOR + "?" );

        if( FormatConverter.isNotEmptyString( paramArray[0] ) )
        {
            sbRequetUrl.append( "merchant_name=" + paramArray[0] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[1] ) )
        {
            sbRequetUrl.append( "parent_categories[]=" + paramArray[1] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[2] ) && !"-1".equals( paramArray[2] ) )
        {
            sbRequetUrl.append( "sub_categories[]=" + paramArray[2] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[3] ) && !"-1".equals( paramArray[3] ) )
        {
            sbRequetUrl.append( "cantons[]=" + paramArray[3] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[4] ) && !"0".equals( paramArray[4] ) )
        {
            sbRequetUrl.append( "business_circles[]=" + paramArray[4] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[5] ) )
        {
            sbRequetUrl.append( "average_price[]=" + paramArray[5] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[6] ) )
        {
            sbRequetUrl.append( "max_customer_rate[]=" + paramArray[6] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[7] ) )
        {
            sbRequetUrl.append( "select_type=" + paramArray[7] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[8] ) )
        {
            sbRequetUrl.append( "distance=" + paramArray[8] + "&" );
        }

        if( FormatConverter.isNotEmptyString( paramArray[9] ) )
        {
            sbRequetUrl.append( "sort=" + paramArray[9] + "&" );
        }

        // remove redundant character & or ?
        if( sbRequetUrl.lastIndexOf( "&", sbRequetUrl.length() - 1 ) != -1
            || sbRequetUrl.lastIndexOf( "?", sbRequetUrl.length() - 1 ) != -1 )
        {
            sbRequetUrl.deleteCharAt( sbRequetUrl.length() - 1 );
        }

        HttpResponse res = request( sbRequetUrl.toString(), HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getHomeVendors()
    {
        HttpResponse res = request( URL_JSON_HOME, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getRecommandVendors( String x, String y )
    {
        String gpsAttitude = "?x=" + x + "&y=" + y;
        HttpResponse res = request( URL_JSON_RECOMMAND + gpsAttitude, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getResources()
    {
        HttpResponse res = request( URL_JSON_RESOURCES, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getBankList()
    {
        HttpResponse res = request( URL_JSON_BANK_LIST, HTTP_METHOD_GET );
        return res;
    }

    public HttpResponse getApkVersion()
    {
        HttpResponse res = request( URL_JSON_APK_VERSION, HTTP_METHOD_GET );
        return res;
    }
}
